<template>
  <div class="tree">
    <div class="tree-header">
      <el-input size="large" v-model="deptName" placeholder="请输入年级" clearable prefix-icon="Search" style="margin-bottom: 20px" />
      <el-button type="primary" style="width: 100%" @click="handleAddGrade">添加年级</el-button>
    </div>
    <div class="tree-body" style="margin-top: 10%">
      <el-tree
        :data="majorThree"
        :props="{ label: 'name', children: 'children' }"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="deptTreeRef"
        node-key="id"
        highlight-current
        default-expand-all
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span v-if="node.level === 2" class="actions">
              <el-button link type="danger" icon="Delete" @click.stop="handleDeleteGradeNode(node, data)">删除</el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script setup>
const deptName = ref('')
const deptTreeRef = ref(null)
// 记录最近选中的学院ID，用于添加年级时预填
const selectedDeptId = ref('')

const props = defineProps({
  majorThree: {
    type: Array,
    default: () => ({})
  }
})

const emit = defineEmits(['selectNode', 'addGrade', 'deleteGrade'])

const filterNode = (value, data) => {
  if (!value) return true
  return String(data.name || '')
    .toLowerCase()
    .includes(String(value).toLowerCase())
}

watch(deptName, (val) => {
  deptTreeRef.value && deptTreeRef.value.filter(val)
})

function handleNodeClick(data, node) {
  if (node.level === 1) {
    selectedDeptId.value = data.id
    emit('selectNode', { type: 'dept', id: data.id, name: data.name })
  } else if (node.level === 2) {
    const parentDeptId = node.parent?.data?.id
    selectedDeptId.value = parentDeptId || ''
    emit('selectNode', { type: 'grade', id: data.id, name: data.name, deptId: parentDeptId })
  } else if (node.level === 3) {
    const gradeId = node.parent?.data?.id
    const deptId = node.parent?.parent?.data?.id
    selectedDeptId.value = deptId || ''
    emit('selectNode', { type: 'major', id: data.id, name: data.name, gradeId, deptId })
  }
}

function handleAddGrade() {
  emit('addGrade', { deptId: selectedDeptId.value })
}

function handleDeleteGradeNode(node, data) {
  if (node.level !== 2) return
  const deptId = node.parent?.data?.id
  emit('deleteGrade', { gradeId: data.id, deptId })
}
</script>
<style scoped></style>
